<template>
  <div>
    <el-table :data="filterTableData" style="width: 100%">
      <el-table-column prop="userid" label="id" width="80" />
      <el-table-column prop="email" label="电子邮箱" width="180" />
      <el-table-column prop="nickname" label="名字" width="100" />
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="phone" label="手机号码" />
      <el-table-column prop="birthday" label="生日" />
      <el-table-column prop="register" label="注册时间" />
      <el-table-column prop="profile" label="头像" />
      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="small" placeholder="邮箱搜索" />
        </template>
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- Form -->

    <el-dialog v-model="dialogFormVisible" title="更新用户信息">
      <el-form :model="formData" ref="formRef" :rules="formDataRules">
        <el-form-item label="id" :label-width="formLabelWidth">
          <el-input disabled v-model="formData.userid" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="电子邮箱"
          :label-width="formLabelWidth"
          prop="email"
        >
          <el-input v-model="formData.email" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="名字"
          :label-width="formLabelWidth"
          prop="nickname"
        >
          <el-input v-model="formData.nickname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-select v-model="formData.gender">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="手机号码"
          :label-width="formLabelWidth"
          prop="phone"
        >
          <el-input v-model="formData.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生日" :label-width="formLabelWidth">
          <!-- <el-input v-model="formData.birthday" autocomplete="off" /> -->
          <el-date-picker
            v-model="formData.birthday"
            start-placeholder="2000-01-01"
            type="date"
            placeholder="Select date and time"
          />
        </el-form-item>
        <el-form-item label="注册时间" :label-width="formLabelWidth">
          <el-input disabled v-model="formData.register" autocomplete="off" />
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-input v-model="formData.profile" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdate"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { getUserInfoApi } from "../../api/user";
import { useUserStore } from "../../store/user";
import { ElMessage, ElMessageBox } from "element-plus";
const { updateUserInfo, deleteUserByEmail } = useUserStore();
const search = ref("");
const tableData = reactive([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "100px";
const formData = reactive({
  userid: "",
  email: "",
  nickname: "",
  gender: "",
  phone: "",
  birthday: "",
  register: "",
  profile: "",
});
const getUserInfo = () => {
  getUserInfoApi().then(res=>{
    res.data.forEach((item) => {
      item.birthday =
        item.birthday && new Date(item.birthday).toLocaleDateString();
      item.register =
        item.register && new Date(item.register).toLocaleDateString();
    });
    tableData.push(...res.data);

  }).then(err=>{
    console.log(err);
  })
  // const res = await getUserInfoApi();
};
onMounted(()=>{
  getUserInfo();
})

const filterTableData = computed(() =>
  tableData.filter(
    (data) =>
      !search.value ||
      data.email.toLowerCase().includes(search.value.toLowerCase())
  )
);
const handleEdit = (index, row) => {
  formData.userid = row.userid;
  formData.email = row.email;
  formData.nickname = row.nickname;
  formData.gender = row.gender;
  formData.phone = row.phone;
  formData.birthday = row.birthday;
  formData.register = row.register;
  formData.profile = row.profile;
  dialogFormVisible.value = true;
  console.log(index, row.email);
};

const formDataRules = reactive({
  nickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 16, message: "长度在 2 到 16 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
  ],
  phone: [{ min: 11, max: 11, message: "请输入11位手机号", trigger: "blur" }],
});

const formRef = ref();

const handleDelete = (index, row) => {
  ElMessageBox.confirm("当前操作不可逆，确定继续吗？", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    //确认时，走成功的回调
    deleteUserByEmail(row.email)
      .then((res) => {
        console.log("删除成功");
        ElMessage.success("删除成功");
        //过滤用户列表数据
        tableData.forEach((item, index) => {
          if (item.email === row.email) {
            tableData.splice(index, 1);
          }
        });
      })
      .catch((err) => {
        ElMessage.error("删除失败");
        throw err;
      });
  });
  console.log(index, row);
};

const confirmUpdate = () => {
  formRef.value.validate((isvalidate) => {
    if (isvalidate) {
      //发送请求修改用户数据 需要传递id
      console.log("chegng");
      ElMessageBox.confirm("当前操作修改了信息，确定继续吗？", "Warning", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(formData, "birthday");
        updateUserInfo(formData)
          .then((res) => {
            ElMessage.success("修改成功");
            tableData.forEach((item) => {
              if (item.userid == formData.userid) {
                item.email = formData.email;
                item.nickname = formData.nickname;
                item.gender = formData.gender;
                item.phone = formData.phone;
                item.birthday =
                  formData.birthday &&
                  new Date(formData.birthday).toLocaleDateString();
                item.register =
                  formData.register &&
                  new Date(formData.register).toLocaleDateString();
                item.profile = formData.profile;
              }
            });
            dialogFormVisible.value = false;
          })
          .catch((err) => {
            ElMessage.error("系统繁忙");
            dialogFormVisible.value = false;
          });
      });
      return true;
    } else {
      return false;
    }
  });
};
</script>
